<script setup lang="ts" name="User">
import { debounce } from 'es-toolkit'
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { downloadBlobFile } from '@/utils'
import { warnBox } from '@/utils/utils'
import { getDicts } from '@/api/system/dict/index'
import type { DeptTree, User, UserQueryParams } from '@/api/system/user/type'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { changeUserStatus, listUser, resetUserPwd, delUser, deptTreeSelect, userExport } from '@/api/system/user/index'
import UserUpload from './components/UserUpload.vue'
import EditDialog from './components/EditDialog.vue'
import LeftTree from './components/LeftTree.vue'
import { columnsBase, formOptionsBase } from './data'

const router = useRouter()
const sysNormalDisable = ref<IGetDictsRes>([])
const deptOptions = ref<DeptTree[]>([])
const userUploadOpen = ref<boolean>(false)

// form
const formValue = ref<UserQueryParams & { daterange?: string[] }>({
	userName: '',
	phoneNumber: '',
	status: '',
	daterange: []
})

const formOptions = ref<FormItemRows[]>([...formOptionsBase])

// table
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<User[]>([])
const columns = ref<TableColums[]>([...columnsBase])
// dialog
const editDialogRef = useTemplateRef('editDialogRef')

const treeClick = (data: DeptTree) => {
	formValue.value.deptId = data.id
	page.value.currentPage = 1
	getTableData()
}
// 导入
const handleImport = () => {
	userUploadOpen.value = true
}

const handleExport = debounce(() => exportFn(), 800, {
	edges: ['leading']
})

// 导出
const exportFn = () => {
	const params = {
		pageNum: page.value.currentPage,
		pageSize: page.value.pageSize,
		...formValue.value,
		'params[beginTime]': formValue.value.daterange?.[0],
		'params[endTime]': formValue.value.daterange?.[1]
	}
	delete params.daterange
	userExport(params).then(data => {
		downloadBlobFile(data.data, data.filename ? data.filename : `user_${new Date().getTime()}.xlsx`)
	})
}
// 重置密码
const handelReset = (row: User) => {
	ElMessageBox.prompt(`请输入"${row.userName}"的新密码`, {
		title: '提示',
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		closeOnClickModal: false,
		inputPattern: /^.{5,20}$/,
		inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
		inputValidator: value => {
			if (/<|>|"|'|\||\\/.test(value)) {
				return '不能包含非法字符：< > " \' \\ |'
			} else {
				return true
			}
		}
	})
		.then(({ value }) => {
			resetUserPwd(row.id!, value).then(() => {
				ElMessage.success(`修改成功，新密码是：${value}`)
			})
		})
		.catch(() => {})
}

const handleAuthRole = (row: User) => {
	router.push(`/system/user-auth/role/${row.id}`)
}

const handleStatusChange = (row: User) => {
	const preStatus = row.status === 0 ? 1 : 0
	const flagMsg = row.status === 0 ? '启用' : '停用'

	ElMessageBox({
		title: '提示',
		type: 'warning',
		message: `确认要"${flagMsg}""${row.userName}"用户吗?`,
		showCancelButton: true,
		cancelButtonText: '取消',
		confirmButtonText: '确定'
	})
		.then(async () => {
			await changeUserStatus(row.id!, preStatus)
			ElMessage.success(flagMsg + '成功')
			getTableData()
		})
		.catch(() => {
			row.status = preStatus
		})
}

const getTableData = async () => {
	try {
		loading.value = true
		const params = {
			pageNum: page.value.currentPage,
			pageSize: page.value.pageSize,
			...formValue.value,
			'params[beginTime]': formValue.value.daterange?.[0],
			'params[endTime]': formValue.value.daterange?.[1]
		}
		delete params.daterange
		const res = await listUser(params)
		tableData.value = res.data.rows
		page.value.total = res.data.total
	} finally {
		loading.value = false
	}
}

const handelAdd = () => {
	editDialogRef.value?.init('add')
}
const handelEdit = (row: User) => {
	editDialogRef.value?.init('edit', row.id + '')
}
const handelDelete = async (rowId: string) => {
	await warnBox({
		title: '提示',
		message: `是否确认删除用户编号为"${rowId}"的数据项？`
	})
	await delUser(rowId)
	ElMessage.success('删除成功')
	getTableData()
}

const init = async () => {
	await deptTreeSelect().then(response => {
		deptOptions.value = response.data
	})
	await getDicts('sys_sys_normal_disable').then(data => {
		sysNormalDisable.value = data
		formOptions.value[2].options = data
	})
}
onMounted(() => {
	init()
	getTableData()
})
</script>

<template>
	<div class="h-full">
		<el-splitter>
			<el-splitter-panel
				size="16%"
				:min="100"
			>
				<LeftTree
					:dept-options="deptOptions"
					@treeClick="treeClick"
				/>
			</el-splitter-panel>
			<el-splitter-panel :min="200">
				<div class="table-page-box">
					<div class="filter-box">
						<QForm
							inline
							:model="formValue"
							:form-options="formOptions"
							:buttons="['search', 'reset']"
							@search="getTableData"
							@reset="getTableData"
						/>
					</div>
					<div class="table-box">
						<QTable
							:data="tableData"
							:columns="columns"
							:page="page"
							:loading="loading"
							style="width: 100%"
							@pageChange="getTableData"
						>
							<template #headerLeft>
								<el-button
									v-if="checkPermission(['system:user:add'])"
									type="primary"
									@click="handelAdd"
								>
									新增
								</el-button>
								<el-button
									v-if="checkPermission(['system:user:import'])"
									@click="handleImport"
								>
									导入
								</el-button>
								<el-button
									v-if="checkPermission(['system:user:import'])"
									@click="handleExport"
								>
									导出
								</el-button>
							</template>
							<template #action="{ row }">
								<el-button
									v-if="checkPermission(['system:user:edit']) && row.id !== 1111111111"
									type="primary"
									link
									@click="handelEdit(row)"
								>
									修改
								</el-button>

								<el-button
									v-if="checkPermission(['system:user:resetPwd']) && row.id !== 1111111111"
									type="primary"
									link
									@click="handelReset(row)"
								>
									重置密码
								</el-button>
								<el-button
									v-if="checkPermission(['system:user:edit']) && row.id !== 1111111111"
									type="primary"
									link
									@click="handleAuthRole(row)"
								>
									分配角色
								</el-button>
								<el-button
									v-if="checkPermission(['system:user:remove']) && row.id !== 1111111111"
									type="danger"
									link
									@click="handelDelete(row.id)"
								>
									删除
								</el-button>
							</template>
							<template #status="{ row }">
								<el-switch
									v-model="row.status"
									:active-value="0"
									:inactive-value="1"
									@click="handleStatusChange(row)"
								/>
							</template>
						</QTable>
					</div>
					<EditDialog
						ref="editDialogRef"
						:dept-options="deptOptions"
						@refresh="getTableData"
					/>
				</div>
			</el-splitter-panel>
		</el-splitter>
		<UserUpload
			v-model:visible="userUploadOpen"
			@refresh="getTableData"
		/>
	</div>
</template>
